<template>
    <div class="drawerBox">
        <el-drawer v-model="drawerVisible" direction="rtl" size="70%" :show-close="false">
            <template #header>
                <h4>电价配置</h4>
            </template>
            <div class="price-config-container">
                <div v-for="(site, siteIndex) in siteData" :key="siteIndex" class="site-config-item">
                    <div class="title">
                        <div class="line"></div>
                        <div class="site-name">{{ site.siteName }}</div>
                    </div>
                    <el-table :data="site.priceData" border stripe>
                        <el-table-column label="月份" width="120">
                            <template #default="scope">
                                <el-select v-model="scope.row.month" placeholder="请选择月份">
                                    <el-option v-for="month in 12" :key="month" :label="`${month}月`"
                                        :value="month"></el-option>
                                </el-select>
                            </template>
                        </el-table-column>

                        <!-- 买入电价 -->
                        <el-table-column label="买入电价" align="center">
                            <el-table-column label="尖">
                                <template #default="scope">
                                    <el-input v-model="scope.row.buyPrice.peak" placeholder="尖" />
                                </template>
                            </el-table-column>
                            <el-table-column label="峰">
                                <template #default="scope">
                                    <el-input v-model="scope.row.buyPrice.highPeak" placeholder="峰" />
                                </template>
                            </el-table-column>
                            <el-table-column label="平">
                                <template #default="scope">
                                    <el-input v-model="scope.row.buyPrice.normal" placeholder="平" />
                                </template>
                            </el-table-column>
                            <el-table-column label="谷">
                                <template #default="scope">
                                    <el-input v-model="scope.row.buyPrice.valley" placeholder="谷" />
                                </template>
                            </el-table-column>
                            <el-table-column label="深谷">
                                <template #default="scope">
                                    <el-input v-model="scope.row.buyPrice.deepValley" placeholder="深谷" />
                                </template>
                            </el-table-column>
                        </el-table-column>

                        <!-- 卖出电价 -->
                        <el-table-column label="卖出电价" align="center">
                            <el-table-column label="尖">
                                <template #default="scope">
                                    <el-input v-model="scope.row.sellPrice.peak" placeholder="尖" />
                                </template>
                            </el-table-column>
                            <el-table-column label="峰">
                                <template #default="scope">
                                    <el-input v-model="scope.row.sellPrice.highPeak" placeholder="峰" />
                                </template>
                            </el-table-column>
                            <el-table-column label="平">
                                <template #default="scope">
                                    <el-input v-model="scope.row.sellPrice.normal" placeholder="平" />
                                </template>
                            </el-table-column>
                            <el-table-column label="谷">
                                <template #default="scope">
                                    <el-input v-model="scope.row.sellPrice.valley" placeholder="谷" />
                                </template>
                            </el-table-column>
                            <el-table-column label="深谷">
                                <template #default="scope">
                                    <el-input v-model="scope.row.sellPrice.deepValley" placeholder="深谷" />
                                </template>
                            </el-table-column>
                        </el-table-column>
                    </el-table>

                    <div class="add-row-btn">
                        <el-button @click="addRow(site)">添加月份</el-button>
                        <el-button @click="resetSiteData(site)">重置</el-button>
                        <el-button type="primary" @click="saveSiteData(site)">保存</el-button>
                    </div>
                </div>
            </div>
        </el-drawer>
    </div>
</template>

<script lang="ts" setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
    visible: {
        type: Boolean,
        default: false
    },
    selectedSites: {
        type: Array,
        default: () => []
    }
})

const emit = defineEmits(['update:visible'])

// 使用计算属性双向绑定visible
const drawerVisible = computed({
    get: () => props.visible,
    set: (val) => emit('update:visible', val)
})

// 存储站点配置数据
const siteData = ref<any[]>([])

// 存储原始站点数据，用于重置功能
const originalSiteData = ref<any[]>([])

// 创建空的价格行数据
const createEmptyPriceRow = () => {
    return {
        month: 1,
        buyPrice: {
            peak: '',
            highPeak: '',
            normal: '',
            valley: '',
            deepValley: ''
        },
        sellPrice: {
            peak: '',
            highPeak: '',
            normal: '',
            valley: '',
            deepValley: ''
        }
    }
}

// 监听选中站点变化，初始化数据
watch(
    () => props.selectedSites,
    (newSites) => {
        if (newSites && newSites.length) {
            const newSiteData = newSites.map((site: any) => ({
                siteName: site.siteName,
                siteId: site.id,
                priceData: [createEmptyPriceRow()]
            }))

            siteData.value = newSiteData

            // 深拷贝保存原始数据，用于重置
            originalSiteData.value = JSON.parse(JSON.stringify(newSiteData))
        } else {
            siteData.value = []
            originalSiteData.value = []
        }
    },
    { immediate: true, deep: true }
)

// 添加行
const addRow = (site: any) => {
    site.priceData.push(createEmptyPriceRow())
}

// 删除行
const removeRow = (site: any, index: number) => {
    site.priceData.splice(index, 1)
    if (site.priceData.length === 0) {
        // 如果没有行了，添加一个空行
        site.priceData.push(createEmptyPriceRow())
    }
}

// 重置单个站点数据
const resetSiteData = (site: any) => {
    // 查找对应的原始站点数据
    const originalSite = originalSiteData.value.find(
        (original) => original.siteId === site.siteId
    )

    if (originalSite) {
        // 使用深拷贝替换当前站点的数据
        const siteIndex = siteData.value.findIndex((s) => s.siteId === site.siteId)
        if (siteIndex !== -1) {
            siteData.value[siteIndex] = JSON.parse(JSON.stringify(originalSite))
            ElMessage.success(`已重置 ${site.siteName} 的电价配置`)
        }
    }
}

// 保存单个站点数据
const saveSiteData = (site: any) => {
    // 数据验证
    const hasInvalidData = site.priceData.some((row: any) => {
        const buyPriceValues = Object.values(row.buyPrice)
        const sellPriceValues = Object.values(row.sellPrice)

        // 检查是否有任何一个价格为空
        return buyPriceValues.some((v: any) => v === '') ||
            sellPriceValues.some((v: any) => v === '')
    })

    if (hasInvalidData) {
        ElMessage.warning('请填写完整的电价数据')
        return
    }

    // 在实际应用中，这里会调用API保存数据
    console.log('保存站点数据:', site)

    // 更新原始数据，以便后续重置功能使用最新保存的数据
    const index = originalSiteData.value.findIndex((s) => s.siteId === site.siteId)
    if (index !== -1) {
        originalSiteData.value[index] = JSON.parse(JSON.stringify(site))
    }

    ElMessage.success(`${site.siteName} 的电价配置已保存`)
}
</script>

<style lang="scss" scoped>
.drawerBox {
    :deep(.el-drawer__header) {
        margin-bottom: 0;
        border-bottom: 1px solid #E5E6EA;
        padding: 0.1rem 0.16rem;

        h4 {
            font-weight: 700;
            color: #000;
        }
    }
}

.price-config-container {

    .site-config-item {
        margin-bottom: 0.3rem;
        border: 2px solid #E5E6EA;
        box-shadow: 0px 4px 4px 0px #022A6440;
        padding: 0.12rem 0.16rem;

        .title {
            display: flex;
            align-items: center;
            margin-bottom: 0.1rem;

            .line {
                width: 3px;
                height: 0.16rem;
                background-color: #046AF9;
                margin-right: 0.06rem;
                border-radius: 4px;
            }

            .site-name {
                font-size: 0.16rem;
                font-weight: 500;
                color: #0355C7;
            }
        }

        .add-row-btn {
            margin-top: 0.1rem;
            display: flex;
            justify-content: right;

            .el-button {
                height: 0.4rem;
            }
        }
    }
}
</style>
